const audio = wx.getBackgroundAudioManager()
const {
  globalData
} = getApp()
Page({
  data: {
    musics: [],
    prevId:""
  },
  onLoad() {

  },
  handleSubmit(event) {
    var keyword = event.detail.value.keyword;
    wx.request({
      url: `http://47.108.197.28:3000/search?keywords=${keyword}`,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        var songs = res.data.result.songs;
        var musics = []
        songs.forEach(item => {
          var obj = {};
          obj.name = item.name;
          obj.id = item.id;
          obj.artistName = item.artists[0].name;
          obj.time = item.duration;
          obj.isPlay = false;
          obj.musicUrl = `https://music.163.com/song/media/outer/url?id=${item.id}`
          musics.push(obj)
        })
        this.setData({
          musics
        })
      }
    });
  },
  handlePlay(event){
    var id = event.currentTarget.dataset.aid;
    var prevId = this.data.prevId;
    var musics = this.data.musics;
    /*1、 id不一样则执行播放 */
    if(id!=prevId){
        musics.forEach(item=>{
          if(item.id== id){
            item.isPlay = true;
          }else{
            item.isPlay =  false;
          }
        })
        this.setData({
          prevId:id,
          musics
        })
    }else{
      /* 2、id相同 */
        // console.log(id)
        musics.forEach(item=>{
          if(item.id==id){
             item.isPlay = !item.isPlay;
             console.log(item.isPlay)
          }
        })
        this.setData({
          musics
        })
    }
  }

})